<template>
  <el-dialog
    v-model="dialogVisible"
    title="新建文件夹"
    width="400px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <!-- 父文件夹信息 -->
    <div class="parent-folder-info" v-if="parentFolderName">
      <el-alert
        :title="parentFolderAlertTitle"
        type="info"
        :closable="false"
        show-icon
      />
    </div>
    
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="文件夹名" prop="folderName">
        <el-input
          v-model="form.folderName"
          placeholder="请输入文件夹名称"
          maxlength="50"
          show-word-limit
          @keyup.enter="handleSubmit"
        />
      </el-form-item>
      
      <el-form-item label="文件夹类型" prop="folderType">
        <el-radio-group v-model="form.folderType">
          <el-radio label="personal">个人文件夹</el-radio>
          <el-radio label="shared">共享文件夹</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="访问级别" prop="accessLevel">
        <el-select v-model="form.accessLevel" placeholder="请选择访问级别">
          <el-option label="私有" value="private" />
          <el-option label="公开" value="public" />
          <el-option label="受限" value="restricted" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          placeholder="请输入文件夹描述（可选）"
          :rows="3"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="loading"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { folderApi } from '@/api/cd'
import type { CdFolderVo } from '@/types/cd'

interface Props {
  visible: boolean
  parentId: number | string
  folderTree?: CdFolderVo[]
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'create-success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 计算父文件夹名称
const parentFolderName = computed(() => {
  if (props.parentId === 0 || props.parentId === '0') {
    return '根目录'
  }
  
  // 从文件夹树中查找父文件夹名称
  const findFolderName = (folders: CdFolderVo[], targetId: number | string): string | null => {
    for (const folder of folders) {
      if (String(folder.folderId) === String(targetId)) {
        return folder.folderName
      }
      if (folder.children && folder.children.length > 0) {
        const found = findFolderName(folder.children, targetId)
        if (found) return found
      }
    }
    return null
  }
  
  if (props.folderTree && props.folderTree.length > 0) {
    const folderName = findFolderName(props.folderTree, props.parentId)
    return folderName || `文件夹 ${props.parentId}`
  }
  
  return `文件夹 ${props.parentId}`
})

// 计算父文件夹提示标题
const parentFolderAlertTitle = computed(() => {
  return `将在文件夹 "${parentFolderName.value}" 下创建新文件夹`
})

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 表单引用
const formRef = ref()

// 加载状态
const loading = ref(false)

// 表单数据
const form = reactive({
  folderName: '',
  folderType: 'personal',
  accessLevel: 'private',
  description: ''
})

// 表单验证规则
const rules = {
  folderName: [
    { required: true, message: '请输入文件夹名称', trigger: 'blur' },
    { min: 1, max: 50, message: '文件夹名称长度在 1 到 50 个字符', trigger: 'blur' },
    { 
      pattern: /^[^<>:"/\\|?*]+$/, 
      message: '文件夹名称不能包含特殊字符 < > : " / \\ | ? *', 
      trigger: 'blur' 
    }
  ],
  folderType: [
    { required: true, message: '请选择文件夹类型', trigger: 'change' }
  ],
  accessLevel: [
    { required: true, message: '请选择访问级别', trigger: 'change' }
  ]
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    loading.value = true
    
    const params = {
      folderName: form.folderName.trim(),
      parentId: props.parentId,
      folderType: form.folderType,
      accessLevel: form.accessLevel,
      description: form.description.trim()
    }
    
    // 使用字符串避免精度丢失
    await folderApi.create(params.folderName, String(params.parentId), undefined)
    
    ElMessage.success('文件夹创建成功')
    emit('create-success')
    handleClose()
    
  } catch (error) {
    if (error !== false) { // 不是表单验证错误
      console.error('创建文件夹失败:', error)
      ElMessage.error('创建文件夹失败')
    }
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  // 重置表单
  form.folderName = ''
  form.folderType = 'personal'
  form.accessLevel = 'private'
  form.description = ''
  
  // 清除验证
  formRef.value?.clearValidate()
  
  dialogVisible.value = false
}
</script>

<style scoped lang="scss">
.parent-folder-info {
  margin-bottom: 16px;
  
  :deep(.el-alert) {
    padding: 12px 16px;
    border-radius: 6px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-textarea__inner) {
  resize: none;
}
</style>
